package cate.game.role.world.invite;

import cate.common.game.invite.InviteDef;
import cate.common.table.d.GDOperation;
import cate.common.table.invite.row.InviteRedPkgRow;
import cate.game.GameBody;
import cate.game.res.MixResAdder;
import cate.game.role.Role;
import easy.java.dev.note.NoteField;
import easy.java.practice.errorcode.EcException;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;

/** 只要是你点击其他玩家分享的链接进入游戏就可以领取元宝红包 */
public class InviteRedPkgTask {
    public List<String> inviters;

    @NoteField(value = "今日已领取过哪些玩家发出的邀请红包", detail = "list中都是一个个的邀请者roleId")
    public List<String> recevied;

    public void init() {
        if (recevied == null) {
            recevied = new ArrayList<>();
        }
        if (inviters == null) {
            inviters = new ArrayList<>();
        }
    }

    public void addInvitor(String loginInviterId) {
        if (inviters.size() >= InviteDef.getRedPkgTaskNumMax()) {
            return;
        }
        if (inviters.contains(loginInviterId)) {
            return;
        }
        inviters.add(loginInviterId);
    }

    public void reset() {
        this.recevied.clear();
        this.inviters.clear();
    }

    private String getRewardCnf(GameBody game, int tid) {
        InviteRedPkgRow row = game.table.invite.redPkg.get(tid);
        if(row == null) {
            throw new EcException("找不到第"+tid+"项InviteRedPkgRow");
        }
        return row.rwdCnf;
    }

    public void tryGetReward(Role role, String loginInviterId) {
        if(StringUtils.isBlank(loginInviterId)) {
            throw new EcException("你本次没有通过别人的邀请进入游戏，无法领取红包").s();
        }
        if(recevied.size() >= InviteDef.getRedPkgTaskNumMax()) {
            throw new EcException("已达到登录邀请红包领取上限，明天再领取吧！").s();
        }
        if(recevied.contains(loginInviterId)) {
            throw new EcException("你今日已经领取过对方赠与你的登录邀请红包了").s();
        }
        String rwdCnf = getRewardCnf(role.getGame(), recevied.size() + 1);
        if(StringUtils.isBlank(rwdCnf)) {
            throw new EcException("没有配置对应奖励").s();
        }
        recevied.add(loginInviterId);
        new MixResAdder()
                .setRes(rwdCnf)
                .setOperation(GDOperation.INVITE)
                .setOperationSub(InviteDef.OPERATION_SUB_RED_PKG)
                .setDialogReward(true)
                .exe(role);
    }
}
